package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.*;
import cn.wolfcode.wms.mapper.ProductStockMapper;
import cn.wolfcode.wms.mapper.SaleAccountMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillMapper;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IStockOutcomeBillService;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService {
    @Autowired
    private StockOutcomeBillMapper stockOutcomebillMapper;
    @Autowired
    private StockOutcomeBillItemMapper stockOutcomeBillItemMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private SaleAccountMapper saleAccountMapper;

    @Override
    public void saveOrUpdate(StockOutcomeBill entity) {
        if (entity.getId() != null) {
            updateBill(entity);
        } else {
           saveBill(entity);
        }
    }
    //更新单据的业务操作
    private  void updateBill(StockOutcomeBill entity){
        //判断当前单据必须是为审核状态
        StockOutcomeBill old = stockOutcomebillMapper.selectByPrimaryKey(entity.getId());
        //删除旧的明细插入新的明细
        stockOutcomebillMapper.deleItemsByBillId(entity.getId());
        if (old.getStatus() ==0) {
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (StockOutcomeBillItem item : entity.getItems()) {
                BigDecimal number = item.getNumber();
                BigDecimal amount = item.getSalePrice().multiply(number).setScale(2,RoundingMode.HALF_UP);
                totalNumber =totalNumber.add(number);
                totalAmount = totalAmount.add(amount);

                item.setBillId(entity.getId());
                item.setTotalAmount(amount);
                stockOutcomeBillItemMapper.insert(item);
                //保存到数据库
            }
            old.setTotalNumber(totalNumber);
            old.setTotalAmount(totalAmount);
            old.setSn(entity.getSn());
            old.setClient(entity.getClient());
            old.setVdate(entity.getVdate());
            old.setDepot(entity.getDepot());
            stockOutcomebillMapper.updateByPrimaryKey(old);
        }
        //将新的数据设置到old
    }

    //新增单据的业务操作
    private  void saveBill(StockOutcomeBill entity){
        //1.状态 2.录入人 3.录入时间
        entity.setStatus(StockOutcomeBill.NOTAUDIT);
        entity.setInputUser(UserContext.getCurrentUser());
        entity.setInputTime(new Date());

        //entity.getId()
        //2:重新后台计算明细的小计
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (StockOutcomeBillItem item : entity.getItems()) {
            BigDecimal number = item.getNumber();
            BigDecimal amount = item.getSalePrice().multiply(number).setScale(2,RoundingMode.HALF_UP);
            totalNumber =totalNumber.add(number);
            totalAmount = totalAmount.add(amount);

            //保存到数据库
        }
        entity.setTotalNumber(totalNumber);
        entity.setTotalAmount(totalAmount);
            stockOutcomebillMapper.insert(entity);

        //先保存订单在保存明细
        for (StockOutcomeBillItem item : entity.getItems()) {
            item.setBillId(entity.getId());
            BigDecimal number = item.getNumber();
            BigDecimal amount = item.getSalePrice().multiply(number).setScale(2,RoundingMode.HALF_UP);
            item.setTotalAmount(amount);
            stockOutcomeBillItemMapper.insert(item);
        }

    }

    @Override
    public void delete(Long id) {
        if (id != null) {
            stockOutcomebillMapper.deleItemsByBillId(id);
            stockOutcomebillMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public StockOutcomeBill get(Long id) {

            StockOutcomeBill entity = stockOutcomebillMapper.selectByPrimaryKey(id);
        return entity;

    }

    @Override
    public List<StockOutcomeBill> selectall() {
        List<StockOutcomeBill> depts = stockOutcomebillMapper.selectAll();
        return depts;
    }

    @Override
    //审核
    public void audit(Long id) {
        //判断为审核状态
        StockOutcomeBill bill = stockOutcomebillMapper.selectByPrimaryKey(id);
        if (bill.getStatus()==1) {
            //表示已经审核,无需再审核
            return;
        }
        //拿到出库明细与库存数据 判断仓库中是否有该商品,如果有出库是数量仓库中是否足够
        //拿到库存数据
        Depot depot = bill.getDepot();

        List<StockOutcomeBillItem> items = bill.getItems();
        for (StockOutcomeBillItem item : items) {
            Product product = item.getProduct();
            ProductStock productStock = productStockMapper.selectByDepotIdAndProductId(depot.getId(), product.getId());
            if (productStock == null) {
                //仓库中没有有库存
                throw  new RuntimeException("仓库:"+depot.getName()+"中没有商品:"+product.getName()+"的库存");
            }
            //判断仓库中是否有足够的数量
            if (item.getNumber().compareTo(productStock.getStoreNumber())>0) {
                //仓库没有足够的数量
                throw  new RuntimeException("仓库:"+depot.getName()+"中商品:"+product.getName()+"的库存是:"+productStock.getStoreNumber()+",不足出库的数量:"+item.getNumber());
            }
            //有足够的数量,出库,更改库存量  且记录销售账
            //更改库存,只需要更改数量和总价值
            BigDecimal totalNumber = productStock.getStoreNumber().subtract(item.getNumber());
            BigDecimal totalAmount = productStock.getAmount().subtract(item.getNumber()
                    .multiply(item.getSalePrice()).setScale(2,RoundingMode.HALF_UP));
            productStock.setStoreNumber(totalNumber);
            productStock.setAmount(totalAmount);
            //更新库存量
            productStockMapper.updateByPrimaryKey(productStock);
            //记录销售账
            SaleAccount sa = new SaleAccount();
            sa.setVdate(bill.getVdate());
            sa.setNumber(item.getNumber());
            sa.setCostPrice(productStock.getPrice());
            sa.setCostAmount(productStock.getPrice().multiply(item.getNumber())
                    .setScale(2,RoundingMode.HALF_UP));
            sa.setSalePrice(item.getSalePrice());
            sa.setSaleAmount(item.getSalePrice().multiply(item.getNumber())
                    .setScale(2,RoundingMode.HALF_UP));
            sa.setProduct(product);
            sa.setSaleman(bill.getInputUser());
            sa.setClient(bill.getClient());
            //存入销售账
            saleAccountMapper.insert(sa);


        }
        //更新审核信息 审核人 审核时间 状态
        bill.setAuditor(UserContext.getCurrentUser());
        bill.setAuditTime(new Date());
        bill.setStatus(StockOutcomeBill.AUDIT);
        stockOutcomebillMapper.audit(bill);



    }

    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = stockOutcomebillMapper.rows(qo);
        if (rows == 0) {
            return PageResult.EMPTY_RESULT;

        }
        PageResult result = new PageResult(qo.getCurrentPage(), qo.getPageSize(), rows, stockOutcomebillMapper.queryForList(qo));
        System.out.println(66);
        return result;

    }
}
